package com.xz.audit.service.impl;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xz.audit.dto.AuditNodeDto;
import com.xz.common.core.domain.AjaxResult;
import com.xz.common.core.domain.model.LoginUser;
import com.xz.common.utils.DateUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xz.common.utils.SecurityUtils;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.xz.audit.mapper.AuditNodeMapper;
import com.xz.audit.domain.AuditNode;
import com.xz.audit.service.IAuditNodeService;
import org.springframework.util.CollectionUtils;

/**
 * 审核Service业务层处理
 *
 * @author xz
 * @date 2023-09-27
 */
@Service
public class AuditNodeServiceImpl extends ServiceImpl<AuditNodeMapper, AuditNode> implements IAuditNodeService {
    @Autowired
    private AuditNodeMapper auditNodeMapper;

    /**
     * 查询审核
     *
     * @param id 审核主键
     * @return 审核
     */
    @Override
    public AuditNode selectAuditNodeById(Long id) {
        AuditNode node = auditNodeMapper.selectAuditNodeById(id);
        List<AuditNode> auditNodeList = baseMapper.selectList(new QueryWrapper<AuditNode>().orderByAsc("audit_sort"));
        List<AuditNode> nodeList = auditNodeList.stream().filter(i -> node.getAuditSort() > i.getAuditSort()).sorted(Comparator.comparing(AuditNode::getAuditSort).reversed()).collect(Collectors.toList());
        if(!CollectionUtils.isEmpty(nodeList)){
            AuditNode auditNode = nodeList.get(0);
            node.setBeforeId(auditNode.getId());
        }
        return node;
    }

    /**
     * 查询审核列表
     *
     * @param auditNode 审核
     * @return 审核
     */
    @Override
    public List<AuditNodeDto> selectAuditNodeList(AuditNode auditNode) {
        List<AuditNodeDto> nodeDtoList = auditNodeMapper.selectAuditNodeList(auditNode);
        nodeDtoList.stream().forEach(i->{
            if(i.getAuditSort()>1){
                List<AuditNode> auditNodeList = auditNodeMapper.selectList(new QueryWrapper<AuditNode>().eq("process_id", auditNode.getProcessId()).eq("audit_sort", i.getAuditSort() - 1));
                if(!CollectionUtils.isEmpty(auditNodeList)){
                    i.setBeforeId(auditNodeList.get(0).getId());
                }
            }
        });

        return nodeDtoList;
    }

    /**
     * 新增审核
     *
     * @param auditNode 审核
     * @return 结果
     */
    @Override
    public AjaxResult insertAuditNode(AuditNode auditNode) {
        List<AuditNode> auditNodeList = baseMapper.selectList(new QueryWrapper<AuditNode>().orderByAsc("audit_sort"));
        LoginUser loginUser = SecurityUtils.getLoginUser();
        auditNode.setCreateTime(DateUtils.getNowDate());
        auditNode.setCreateBy(loginUser.getUserId());
        auditNode.setTenantId(loginUser.getTenantId());
        //是否有上级节点
        if(auditNode.getBeforeId() !=null){//有上级
            //上节点数据
            AuditNode node = baseMapper.selectById(auditNode.getBeforeId());
            if(Objects.isNull(node)){
                return AjaxResult.error("新增节点失败");
            }
            int sortNum = node.getAuditSort() + 1;
            auditNode.setAuditSort(sortNum);
            auditNodeMapper.insertAuditNode(auditNode);
            //后面节点进行递增排序
            List<AuditNode> nodeList = auditNodeList.stream().filter(i -> i.getAuditSort() > node.getAuditSort()).collect(Collectors.toList());
            for(AuditNode sort:nodeList){
                sortNum++;
                sort.setAuditSort(sortNum);
                auditNodeMapper.updateAuditNode(sort);
            }
        }else{//无上级
            //当前类型是否有第一级
            Integer count = baseMapper.selectCount(new QueryWrapper<AuditNode>().eq("process_id", auditNode.getProcessId()).eq("audit_sort", 1));
            if(count>0){
                return AjaxResult.error("当前流程已存在一级节点，请选择上级节点");
            }
            int sortNum = 1;
            auditNode.setAuditSort(sortNum);
            auditNodeMapper.insertAuditNode(auditNode);
            //后面节点进行递增排序
            for(AuditNode sort:auditNodeList){
                sortNum++;
                sort.setAuditSort(sortNum);
                auditNodeMapper.updateAuditNode(sort);
            }
        }
        return AjaxResult.success("新增节点成功");
    }

    /**
     * 修改审核
     *
     * @param auditNode 审核
     * @return 结果
     */
    @Override
    public AjaxResult updateAuditNode(AuditNode auditNode) {
        if(auditNode.getAuditId()==null){
            return AjaxResult.error("参数不能为空");
        }

        auditNode.setUpdateTime(DateUtils.getNowDate());
        auditNode.setUpdateBy(SecurityUtils.getUserId());

        List<AuditNode> auditNodeList = baseMapper.selectList(new QueryWrapper<AuditNode>().orderByAsc("audit_sort"));
        //是否有上级节点
        if(auditNode.getBeforeId() !=null){//有上级
            //取出要调整的数据
            List<AuditNode> beforeList = auditNodeList.stream().filter(i -> !Objects.equals(i.getId(), auditNode.getId())).collect(Collectors.toList());
            if(!CollectionUtils.isEmpty(beforeList)){
                Integer num=1;
                for(AuditNode sort:beforeList){
                    sort.setAuditSort(num);
                    num++;
                }
            }
            //上节点数据
            List<AuditNode> auditNodes = beforeList.stream().filter(i -> Objects.equals(i.getId(), auditNode.getBeforeId())).collect(Collectors.toList());
            if(CollectionUtils.isEmpty(auditNodes)){
                return AjaxResult.error("修改节点失败");
            }
            AuditNode node = auditNodes.get(0);
            int sortNum = node.getAuditSort() + 1;
            auditNode.setAuditSort(sortNum);
            auditNodeMapper.updateAuditNode(auditNode);
            //调整其他节点排序
            List<AuditNode> nodeList = beforeList.stream().filter(i ->   i.getAuditSort()>=auditNode.getAuditSort()).collect(Collectors.toList());
            for(AuditNode sort:nodeList){
                sortNum++;
                sort.setAuditSort(sortNum);
            }
            if(!CollectionUtils.isEmpty(nodeList)){
                this.updateBatchById(nodeList);
            }else{
                this.updateBatchById(beforeList);
            }
        }else{//无上级
            int sortNum = 1;
            auditNode.setAuditSort(sortNum);
            auditNodeMapper.updateAuditNode(auditNode);
            //取出要调整的数据
            List<AuditNode> beforeList = auditNodeList.stream().filter(i -> !Objects.equals(i.getId(), auditNode.getId())).collect(Collectors.toList());
            if(!CollectionUtils.isEmpty(beforeList)){
                Integer num=sortNum+1;
                //后面节点进行递增排序
                for(AuditNode sort:beforeList){
                    sort.setAuditSort(num);
                    num++;
                }
                //调整其他节点排序
                this.updateBatchById(beforeList);
            }
        }
        return AjaxResult.success("修改节点成功");
    }

    /**
     * 批量删除审核
     *
     * @param ids 需要删除的审核主键
     * @return 结果
     */
    @Override
    public AjaxResult deleteAuditNodeByIds(Long[] ids) {
        int deleteAuditNodeById = auditNodeMapper.deleteAuditNodeByIds(ids);
        if(deleteAuditNodeById>0){
            List<AuditNode> auditNodeList = baseMapper.selectList(new QueryWrapper<AuditNode>().orderByAsc("audit_sort"));
            int sortNum=1;
            for(AuditNode sort:auditNodeList){
                sort.setAuditSort(sortNum);
                auditNodeMapper.updateAuditNode(sort);
                sortNum++;
            }
        }
        return AjaxResult.success("删除成功");
    }

    /**
     * 删除审核信息
     *
     * @param id 审核主键
     * @return 结果
     */
    @Override
    public AjaxResult deleteAuditNodeById(Long id) {
        int deleteAuditNodeById = auditNodeMapper.deleteAuditNodeById(id);
        if(deleteAuditNodeById>0){
            List<AuditNode> auditNodeList = baseMapper.selectList(new QueryWrapper<AuditNode>().orderByAsc("audit_sort"));
            int sortNum=1;
            for(AuditNode sort:auditNodeList){
                sort.setAuditSort(sortNum);
                auditNodeMapper.updateAuditNode(sort);
                sortNum++;
            }
        }
        return AjaxResult.success("删除成功");
    }

    /**
     * 节点明细
     * @param auditNode
     * @return
     */
    @Override
    public List<Map<String, Objects>> getSortList(AuditNode auditNode) {
        return baseMapper.getSortList(auditNode);
    }
}
